import * as React from 'react';
import { Col, Row, Divider, notification } from 'antd';
import { useState } from 'react';
import LicForm from '@/components/LicForm';
import LicCode from '@/components/LicCode';
import Client, { Request, Response } from '@/client';
import styles from './style.less';

export interface Result {
  /**
   * @description 响应的文件名称
   */
  fileName: string;
  /**
   * @description 截止时间
   */
  deadline: string;
  /**
   * @description 文件内容
   */
  contents: string;
  /**
   * @description 错误编码
   */
  code: string | null;
  /**
   * @description 错误信息
   */
  message: string;
}

export interface FineLicProps {
  host?: string;
  port?: number;
}

const FineLic: React.FC<FineLicProps> = (props) => {
  const { host, port } = props;
  const client = new Client();
  client.config({ host, port });
  const [result, setResult] = useState<Partial<Result>>({});
  const submit = async (values: Request) => {
    console.log('submit contents:', values);
    try {
      const res: Response = await client.send(values);
      const { fileName, deadLine: deadline, contents } = res;
      setResult({
        fileName,
        deadline,
        contents: atob(contents as string), // base64 解码
      });
    } catch (e) {
      const { message } = e;
      notification.destroy();
      notification.error({ message: '请求异常', description: message || '网络异常', duration: null });
    }
  };

  return (
    <div className={`${styles.app}`}>
      <Row justify="center">
        <h1 className={styles.title}>帆软授权 Web 客户端</h1>
      </Row>
      <Row>
        <Col xs={{ span: 24 }} lg={{ span: 14 }} className={styles.col}>
          <div className={styles.form}>
            <LicForm submit={submit} />
          </div>
        </Col>
        <Col xs={{ span: 24 }} sm={{ span: 24 }} lg={{ span: 0 }}>
          <Divider className={styles.divider} dashed style={{}} />
        </Col>
        <Col xs={{ span: 24 }} sm={{ span: 24 }} lg={{ span: 10 }} className={styles.code}>
          <LicCode result={result} />
        </Col>
      </Row>
    </div>
  );
};

FineLic.defaultProps = {
  host: LIC_SERVER_HOST || 'localhost',
  port: LIC_SERVER_PORT || 8189,
};

export default FineLic;
